package org.xiaojl.config.quartz;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xiaojl.modules.task.entity.TaskJob;
import org.xiaojl.utils.SpringUtil;
import org.xiaojl.utils.ToolUtil;

/**
 * 定时任务调度工具类
 */
public class ScheduleJobUtil {
	public final static Logger logger = LoggerFactory.getLogger(ScheduleJobUtil.class);

	/**
	 * 通过反射调用TaskJob中定义的方法
	 */
	public static void invokMethod(TaskJob scheduleJob) {
		Object object = null;
		Class clazz = null;
		try {
			try {
				if (!ToolUtil.isEmpty(scheduleJob.getBeanId())){
					object = SpringUtil.getBean(scheduleJob.getBeanId());
				}
			} catch (Exception e) {
				logger.info("任务：" + scheduleJob.getJobName() + "，未注入到Spring容器中！");
			}
			
			if (!ToolUtil.isEmpty(scheduleJob.getBeanClass())) {
				clazz = Class.forName(scheduleJob.getBeanClass());
				object = clazz.newInstance();
			}
			if (object == null) {
				logger.error("任务：" + scheduleJob.getJobName() + "，结果:执行失败！");
				return;
			}
			clazz = object.getClass();
			Method method = null;
			method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
			if (method != null) {
				method.invoke(object);
			} else {
				logger.error("任务：" + scheduleJob.getJobName() + "，结果:执行失败！");
				return;
			}
			logger.info("任务：" + scheduleJob.getJobName() + "，结果:执行成功！");
		} catch (Exception e) {
			logger.error("任务：" + scheduleJob.getJobName() + "，结果:执行失败！，原因:" + e.getMessage());
		}
	}
}
